package io.renren.modules.lucky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.app.constants.StringConstants;
import io.renren.modules.app.form.out.AppCommentListForm;
import io.renren.modules.app.form.out.AppGoodsInfoForm;
import io.renren.modules.app.form.out.AppGoodsInfoListForm;
import io.renren.modules.lucky.dao.AppGoodsAddrDao;
import io.renren.modules.lucky.dao.AppGoodsCommentDao;
import io.renren.modules.lucky.dao.AppGoodsDzscDao;
import io.renren.modules.lucky.dao.AppGoodsInfoDao;
import io.renren.modules.lucky.entity.AppGoodsInfoEntity;
import io.renren.modules.lucky.service.AppGoodsInfoService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

@Service("appGoodsInfoService")
public class AppGoodsInfoServiceImpl extends ServiceImpl<AppGoodsInfoDao, AppGoodsInfoEntity> implements AppGoodsInfoService {

    @Autowired
    private AppGoodsAddrDao appGoodsAddrDao;

    @Autowired
    private AppGoodsInfoDao appGoodsInfoDao;

    @Autowired
    private AppGoodsCommentDao appGoodsCommentDao;

    @Autowired
    private AppGoodsDzscDao appGoodsDzscDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AppGoodsInfoEntity> page = this.page(
                new Query<AppGoodsInfoEntity>().getPage(params), new QueryWrapper<>()
        );
        List<AppGoodsInfoEntity> list = page.getRecords();
        return new PageUtils(page);
    }

    private Map<String, Map<Integer, Object>> getGoodsInfoCount(List<Integer> ids, String userId) {
        Map<String, Map<Integer, Object>> map = new HashMap<>();
        //查评论数
        List<Map<String, Object>> commList = appGoodsCommentDao.selectCommCountByGoods(ids);
        //查点赞、收藏数
        List<Map<String, Object>> dzscList = appGoodsDzscDao.selectDzscCount(ids);
        //查询是否点赞
        List<Map<String, Object>> myDzscList = appGoodsDzscDao.selectMyDzscCount(ids, userId);
        if (commList.size() > 0) {
            Map<Integer, Object> map1 = new HashMap<>();
            for (Map m : commList) {
                map1.put((Integer) m.get("goods_id"), m.get("count"));
            }
            map.put("comm", map1);
        }
        if (dzscList.size() > 0) {
            Map<Integer, Object> map2 = new HashMap<>();
//            Map<Integer, Object> map3 = new HashMap<>();
            for (Map m : dzscList) {
                map2.put((Integer) m.get("goods_id"), m.get("dz"));
//                map3.put((Integer) m.get("goods_id"), m.get("sc"));
            }
            map.put("dz", map2);
//            map.put("sc", map3);
        }
        if (myDzscList.size() > 0) {
            Map<Integer, Object> map4 = new HashMap<>();
            for (Map m : myDzscList) {
                map4.put((Integer) m.get("goods_id"), m.get("num"));
            }
            map.put("mydz", map4);
        }
        return map;
    }

    @Override
    public List<AppGoodsInfoListForm> queryPageForApp(String curPage, String pageSize, String goodsFlag, String weekType, String userId)
            throws InvocationTargetException, IllegalAccessException {
        //处理分页信息
        if (Integer.parseInt(pageSize) > 7)
            pageSize = "7";
        Date date[] = DateUtils.getWeekStartAndEnd(Integer.parseInt(weekType));
        String startTime = DateUtils.format(date[0], "yyyy-MM-dd"), endTime = DateUtils.format(date[1], "yyyy-MM-dd");
        QueryWrapper<AppGoodsInfoEntity> goodsWrapper = new QueryWrapper<AppGoodsInfoEntity>();
        goodsWrapper.ne("goods_flag", goodsFlag);
        //往期商品
        if ("-1".equals(weekType)) {
            goodsWrapper.lt("start_time", endTime);
            goodsWrapper.orderByDesc("start_time");
        } else {
            goodsWrapper.between("start_time", startTime, endTime);
            goodsWrapper.orderByAsc("start_time");
        }
        goodsWrapper.last("limit " + curPage + "," + pageSize);

        List<AppGoodsInfoEntity> list = baseMapper.selectList(goodsWrapper);
        Assert.isNull(list, "商品列表为空");
        //flag=4 数据Y 开始图X 标签Y 商品图Y 价格Y 中奖人Y 结束图Y（结束商品）
        List<AppGoodsInfoListForm> goodsInfoList = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        for (AppGoodsInfoEntity goodsInfoEntity : list) {
            AppGoodsInfoListForm goodsInfoForm = new AppGoodsInfoListForm();
            //flag=6 数据X 开始图X 标签X 商品图X 价格X 中奖人X 结束图X（下周以后的）
            //flag=5 数据Y 开始图Y 标签Y 商品图X 价格X 中奖人X 结束图X（本周未开始的）
            if (goodsInfoEntity.getGoodsFlag() == 5 || goodsInfoEntity.getGoodsFlag() == 6) {
                goodsInfoEntity.setGoodsShowPrice("XXX");
                goodsInfoEntity.setGoodsImage(StringConstants.defaultImage);
            }
            //flag=2 数据Y 开始图X 标签Y 商品图Y 价格X 中奖人X 结束图X（今天未开始的）
            if (goodsInfoEntity.getGoodsFlag() == 2) {
                goodsInfoEntity.setGoodsShowPrice("XXX");
            }
            //flag=3 数据Y 开始图X 标签Y 商品图Y 价格Y 中奖人X 结束图X（今天已开始的）
            if (goodsInfoEntity.getGoodsFlag() == 3) {
                goodsInfoEntity.setGoodsShowPrice(goodsInfoEntity.getGoodsHiddenPrice());
            }
            BeanUtils.copyProperties(goodsInfoForm, goodsInfoEntity);
            ids.add(goodsInfoEntity.getId());
            goodsInfoList.add(goodsInfoForm);
        }
        Map<String, Map<Integer, Object>> map = getGoodsInfoCount(ids, userId);
        for (AppGoodsInfoListForm form : goodsInfoList) {
            Map<Integer, Object> commMap = map.get("comm");
            Map<Integer, Object> dzscMap = map.get("dz");
            Map<Integer, Object> isDzscMap = map.get("mydz");
            if (commMap != null && commMap.get(form.getId()) != null)
                form.setCommCount(Integer.parseInt(commMap.get(form.getId()).toString()));
            if (dzscMap != null && dzscMap.get(form.getId()) != null)
                form.setDzscCount(Integer.parseInt(dzscMap.get(form.getId()).toString()));
            if (isDzscMap != null && isDzscMap.get(form.getId()) != null)
                form.setIdDzsc(Integer.parseInt(isDzscMap.get(form.getId()).toString()));
        }
        return goodsInfoList;
    }

    @Override
    public List<AppGoodsInfoListForm> queryPageForMyGoods(String curPage, String pageSize, String goodsFlag, String userId)
            throws InvocationTargetException, IllegalAccessException {
        List<AppGoodsInfoEntity> list = appGoodsInfoDao.queryPageForMyGoods(0, Integer.parseInt(userId),
                Integer.parseInt(curPage), Integer.parseInt(pageSize));
        Assert.isNull(list, "商品列表为空");
        List<AppGoodsInfoListForm> goodsInfoList = new ArrayList<>();
        for (AppGoodsInfoEntity goodsInfoEntity : list) {
            AppGoodsInfoListForm goodsInfoForm = new AppGoodsInfoListForm();
            BeanUtils.copyProperties(goodsInfoForm, goodsInfoEntity);
            goodsInfoList.add(goodsInfoForm);
        }
        return goodsInfoList;
    }

    public AppGoodsInfoForm getGoodsInfo(String goodId) throws InvocationTargetException, IllegalAccessException, ParseException {
        AppGoodsInfoForm goodsInfoForm = new AppGoodsInfoForm();
        // 获取商品信息
        AppGoodsInfoEntity goodsInfoEntity = baseMapper.selectOne(new QueryWrapper<AppGoodsInfoEntity>()
                .ne("goods_flag", 0).eq("id", goodId));
        Assert.isNull(goodsInfoEntity, "商品不存在");

        if (goodsInfoEntity.getGoodsFlag() == 5 || goodsInfoEntity.getGoodsFlag() == 6) {
            goodsInfoEntity.setGoodsImage(StringConstants.defaultImage);
            goodsInfoEntity.setGoodsShowPrice("XXX");
        }
        //flag=2 数据Y 开始图X 标签Y 商品图Y 价格X 中奖人X 结束图X（今天未开始的）
        if (goodsInfoEntity.getGoodsFlag() == 2) {
            goodsInfoEntity.setGoodsShowPrice("XXX");
        }
        //flag=3 数据Y 开始图X 标签Y 商品图Y 价格Y 中奖人X 结束图X（今天已开始的）
        if (goodsInfoEntity.getGoodsFlag() == 3) {
            goodsInfoEntity.setGoodsShowPrice(goodsInfoEntity.getGoodsHiddenPrice());
        }
        BeanUtils.copyProperties(goodsInfoForm, goodsInfoEntity);

        // 获取中奖人信息
        Map<String, Object> map = appGoodsAddrDao.getWinnerInfo(goodsInfoEntity.getId());
        // 中奖人信息为空
        if (map != null) {
            goodsInfoForm.setAddrProv(map.get("addr_prov") != null ? map.get("addr_prov").toString() : "");
            goodsInfoForm.setAddrCity(map.get("addr_city") != null ? map.get("addr_prov").toString() : "");
            goodsInfoForm.setAddrDist(map.get("addr_dist") != null ? map.get("addr_prov").toString() : "");
            goodsInfoForm.setAddrInfo(map.get("addr_info") != null ? map.get("addr_prov").toString() : "");
            goodsInfoForm.setAcceptName(map.get("accept_name") != null ? map.get("addr_prov").toString() : "");
            goodsInfoForm.setAcceptPhone(map.get("accept_phone") != null ? map.get("addr_prov").toString() : "");
        }
        // 获取评论信息
        List<Map<String, Object>> list = appGoodsCommentDao.getGoodsCommentList(goodsInfoEntity.getId());
        List<AppCommentListForm> commentListForms = new ArrayList<>();
        if (list != null)
            for (Map<String, Object> commentMap : list) {
                AppCommentListForm commentListForm = new AppCommentListForm();
                commentListForm.setCommentId(commentMap.get("comment_id") != null ? Integer.parseInt(commentMap.get("comment_id").toString()) : 0);
                commentListForm.setCommentContent(commentMap.get("comment_content") != null ? commentMap.get("comment_content").toString() : "");
                commentListForm.setCommentCreateTime(commentMap.get("create_time").toString());
                commentListForm.setUserPortrait(commentMap.get("user_portrait") != null ? commentMap.get("user_portrait").toString() : "");
                commentListForm.setUserNickname(commentMap.get("user_nickname") != null ? commentMap.get("user_nickname").toString() : "");
                commentListForms.add(commentListForm);
            }
        goodsInfoForm.setCommentListForms(commentListForms);
        return goodsInfoForm;
    }

    public int addGoodsInfo(AppGoodsInfoEntity infoEntity) {
        Date date = new Date();
        String nowStr = DateUtils.format(date, "yyyyMMdd");
        // 获取活动开始时间
        String startStr = DateUtils.format(infoEntity.getStartTime(), "yyyyMMdd");
        if (startStr == null)
            startStr = nowStr;
        // 商品录入参数调整
        if (nowStr.equals(startStr))
            infoEntity.setGoodsFlag(2); //未开始状态
        else if (Integer.parseInt(startStr) - Integer.parseInt(nowStr) > 7)
            infoEntity.setGoodsFlag(6); //未上线已创建状态
        else
            infoEntity.setGoodsFlag(5); //明日活动或者是后7天以内的活动，准备开始状态
        infoEntity.setCreateTime(date);
        return baseMapper.insert(infoEntity);
    }

    @Override
    public int addViewCount(Integer id) {
        AppGoodsInfoEntity info = appGoodsInfoDao.selectById(id);
        if (info != null) {
            Integer count = info.getGoodsViewCount();
            if (count == null) {
                count = 0;
            }
            count++;
            info.setGoodsViewCount(count);
            return appGoodsInfoDao.updateById(info);
        }
        return 0;
    }

}